<template>
  <div class="verification">
    <van-field
        v-model="sms"
        center
        clearable
        :left-icon="icon"
        :label="label"
        placeholder="请输入短信验证码"
      @change="changeSms">
      <template #button>
        <van-button size="small" type="primary" style="color:red;background-color: #fff;
        border:none;font-size:.4rem" @click="countDown">{{msg}}</van-button>
    </template>
    </van-field>
  </div>
</template>

<script>
export default {
  name: 'VerificationCode',
  data () {
    return {
      msg: '发送验证码',
      time: 60,
      sms: '',
      icon: 'more-o',
      label: ''
    }
  },
  mounted () {
    const username = localStorage.getItem('username')
    if (username) {
      this.label = '验证码'
      this.icon = ''
    }
    // console.log(username)
  },
  methods: {
    countDown () {
      this.sendMsg()
    },
    sendMsg () {
      //   必变 this 再定时函数内改变
      const me = this
      const interval = window.setInterval(function () {
        me.msg = me.time + '秒后获取'
        --me.time
        // 删除定时函数
        if (me.time < 0) {
          me.msg = '重新发送'
          me.time = 60
          window.clearInterval(interval)
        }
      }, 1000)
    },
    changeSms () {
      console.log(this.sms)
      this.$emit('changeSms', this.sms)
    }
  }
}
</script>

<style>

</style>
